/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ClassMonger;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 *
 * @author User
 */
public class ClassMonger {

    public ClassMonger() {
    }

    public static Class[] getClasses(String packageName, ClassLoader cl)
            throws ClassNotFoundException, IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<File>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        ArrayList<Class> classes = new ArrayList<Class>();
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName, cl));
        }
        return classes.toArray(new Class[classes.size()]);
    }

    public static List<Class> findClasses(File directory, String packageName, ClassLoader cl) throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            String fileName = file.getName();
            if (file.isDirectory()) {
                assert !fileName.contains(".");
                classes.addAll(findClasses(file, packageName + "." + fileName, cl));
            } else if (fileName.endsWith(".class") && !fileName.contains("$")) {
                Class _class;
                try {
                    final String cName = packageName + '.' + fileName.substring(0, fileName.length() - 6);
                    //_class = Class.forName(cName);
                    _class = cl.loadClass(cName);
                } catch (ExceptionInInitializerError e) {
                    // happen, for example, in classes, which depend on 
                    // Spring to inject some beans, and which fail, 
                    // if dependency is not fulfilled
//                    _class = Class.forName(packageName + '.' + fileName.substring(0, fileName.length() - 6),
//                            false, Thread.currentThread().getContextClassLoader());

                    String cName = packageName + '.' + fileName.substring(0, fileName.length() - 6);

                    _class = cl.loadClass(cName);

                }
                classes.add(_class);
            }
        }
        return classes;
    }
}
